/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;

import org.apache.log4j.Logger;

public class CmdUtil {
	
	private final static Logger logger = Logger.getLogger(CmdUtil.class);
	
	/**
	 * TODO: replace with apache commons cmd util
	 * @param cmdarray
	 * @param envp
	 * @return stdout
	 */
	public static String execute(String[] cmdarray, String[] envp) {
		logger.info("Executing: "+Arrays.toString(cmdarray));
		Runtime runtime = null;
		Process process = null;
		InputStream is = null;
	    BufferedReader br = null;
		StringBuffer stdout = new StringBuffer();
//		StringBuffer stdout = new StringBuffer(Arrays.toString(cmdarray)+"\n\n");
		try {
//			ProcessBuilder pb = new ProcessBuilder(cmdarray);
//			pb.redirectErrorStream(true);
//			process = pb.start();
			runtime = Runtime.getRuntime();
            process = runtime.exec( cmdarray, envp );
            //process.waitFor();
			is = process.getInputStream();
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));  
			String line = null;
			while ((line = br.readLine()) != null) {
				stdout.append(line+"\n");
			}
			br.close();
			is.close();
			process.destroy();
		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw); 
			e.printStackTrace( pw );
			stdout.append(sw.toString());
		}
		return stdout.toString();
	}
	
}
